package com.lindroid.androiduilearning.expandablelistview;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;

import com.lindroid.androiduilearning.R;
import com.lindroid.androiduilearning.base.BaseActivity;
import com.lindroid.androiduilearning.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * @author linyulong
 *         动画：https://stackoverflow.com/questions/20627113/android-expandablelistview-using-animation
 *         https://www.cnblogs.com/kingfly13/p/4457260.html
 */
public class ExpandableListViewActivity extends BaseActivity {

    private final int MAJOR_LIST = 1;
    private final int COMMON_USE = 2;

    /**
     * Fragment的集合
     */
    private List<BaseFragment> fragmentList;
    private String[] menuTitles = {"专业选择列表", "普通的使用"};

    /**
     * 上次切换的Fragment
     */
    private BaseFragment currentFragment;

    /**
     * 被选中的fragment的position
     */
    private int selPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_expandable_list_view);
        context = ExpandableListViewActivity.this;
        initBlueToolBar(getString(R.string.expandable_list_view), true);
        //初始化Fragment
        initFragment();
        setFirstFragment();
    }

    private void setFirstFragment() {
        //默认显示第一个Fragment
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.view_content, fragmentList.get(0)).commit();
        //将第一个Fragment记录为当前的Fragment
        currentFragment = fragmentList.get(0);
    }

    private void initFragment() {
        fragmentList = new ArrayList<>();
        fragmentList.add(MajorFragment.newInstance());
        fragmentList.add(CommonFragment.newInstance());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, MAJOR_LIST, 1, menuTitles[0]);
        menu.add(Menu.NONE, COMMON_USE, 2, menuTitles[1]);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MAJOR_LIST:
                selPosition = item.getOrder() - 1;
                break;
            case COMMON_USE:
                selPosition = item.getOrder() - 1;
                break;
            default:
                break;
        }
        //获取position对应的Fragment
        BaseFragment nextFragment = getFragment(fragmentList, selPosition);
        //切换Fragment
        currentFragment = switchFragment(R.id.view_content, currentFragment, nextFragment);
        return super.onOptionsItemSelected(item);
    }
}
